
from django.conf import settings
from django.db import models
from django.contrib.auth import get_user_model
from django.db import models
from django.core.validators import MinLengthValidator, RegexValidator

User = get_user_model()

class Chef(models.Model):
    """客户端展示的厨师模型，应与DjChef保持同步"""
    # 状态选项
    STATUS_CHOICES = (
        ('active', '可接单'),
        ('suspended', '休息中'),
        ('banned', '已禁用'),
    )
    
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='chef_profile')
    djchef = models.OneToOneField('DjChef', on_delete=models.CASCADE, related_name='client_profile')
    
    # 基本信息
    name = models.CharField(max_length=100,default='Chef James')
    avatar = models.URLField(blank=True,null=True)
    specialty = models.CharField(max_length=100,null=True)
    bio = models.TextField(max_length=500, blank=True,null=True)
    
    # 状态信息
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active')
    is_verified = models.BooleanField(default=False)
    
    # 评分信息
    rating = models.FloatField(default=4.5)
    review_count = models.PositiveIntegerField(default=0)
    
    # 位置信息
    city = models.CharField(max_length=100, blank=True,null=True)
    
    # 统计信息
    completed_orders = models.PositiveIntegerField(default=0)
    
    class Meta:
        ordering = ['-rating', '-is_verified']
        
    def __str__(self):
        return f"{self.name} - {self.specialty}"
    
class ChefImage(models.Model):
    chef = models.ForeignKey(Chef, on_delete=models.CASCADE, related_name='images')
    image = models.ImageField(upload_to='chef_images/')
    is_primary = models.BooleanField(default=False)
    uploaded_at = models.DateTimeField(auto_now_add=True)

class ChefCertificate(models.Model):
    chef = models.ForeignKey(Chef, on_delete=models.CASCADE, related_name='certificates')
    name = models.CharField(max_length=255)
    issuing_organization = models.CharField(max_length=255)
    year_obtained = models.PositiveIntegerField()
    certificate_file = models.FileField(upload_to='chef_certificates/', null=True, blank=True)

class ChefReview(models.Model):
    RATING_CHOICES = [
        (1, '1 - Poor'),
        (2, '2 - Fair'),
        (3, '3 - Good'),
        (4, '4 - Very Good'),
        (5, '5 - Excellent'),
    ]
    
    chef = models.ForeignKey(Chef, on_delete=models.CASCADE, related_name='reviews')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.PositiveSmallIntegerField(choices=RATING_CHOICES)
    comment = models.TextField(max_length=1000)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        unique_together = ('chef', 'user')
        ordering = ['-created_at']

class DishCategory(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='dish_categories/')
    description = models.TextField(blank=True) 
    
    class Meta:
        verbose_name = '菜品分类'
        verbose_name_plural = '菜品分类'
    
    def __str__(self):
        return self.name

class Dish(models.Model):
    chef = models.ForeignKey(
        Chef, 
        on_delete=models.CASCADE,
        related_name='dishes'
    )
    category = models.ForeignKey(
        DishCategory,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='dishes'
    )
    name = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=8, decimal_places=2)
    image = models.ImageField(upload_to='dishes/')
    is_spicy = models.BooleanField(default=False)
    prep_time = models.PositiveIntegerField(help_text="准备时间(分钟)")
    is_available = models.BooleanField(default=True)
    
    class Meta:
        verbose_name = '菜品'
        verbose_name_plural = '菜品'
    
    def __str__(self):
        return f"{self.name} - {self.chef.user.username}"
    




#以下是厨师端


class DjChef(models.Model):
    """
    厨师用户模型
    """
    # 认证状态选项
    VERIFICATION_STATUS = (
        ('unverified', '未认证'),
        ('pending', '认证中'),
        ('verified', '已认证'),
        ('rejected', '认证被拒'),
    )
    
    # 用户状态选项
    USER_STATUS = (
        ('active', '活跃'),
        ('suspended', '暂停服务'),
        ('banned', '禁用'),
    )

    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='djchef_profile',
        null=True,
        blank=True
    )
    
    # 基础信息
    openid = models.CharField(
        max_length=64, 
        unique=True,
        validators=[MinLengthValidator(8)],
        verbose_name='微信OpenID'
    )
    username = models.CharField(
        max_length=32, 
        verbose_name='用户名'
    )
    nickname = models.CharField(
        max_length=32, 
        blank=True,
        verbose_name='昵称'
    )
    real_name = models.CharField(
        max_length=32, 
        blank=True,
        verbose_name='真实姓名'
    )
    specialty = models.CharField(max_length=20,null=True,blank=True,verbose_name='国籍')
    bio = models.TextField(max_length=500, blank=True, null=True)
    subscribe_status = models.BooleanField(default=False)  # 订阅状态
    # 认证信息
    verification_status = models.CharField(
        max_length=16,
        choices=VERIFICATION_STATUS,
        default='unverified',
        verbose_name='认证状态'
    )
    verification_submitted_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='认证提交时间'
    )
    verification_processed_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='认证处理时间'
    )
    avatar = models.URLField(
        blank=True,
        null=True,
        verbose_name='头像URL',
        max_length=2000 
    )
    background = models.URLField(
        #upload_to='chef_backgrounds/',
        null=True,
        blank=True,
        verbose_name='背景图URL',
        max_length=2000
    )
    background_approved = models.BooleanField(
        default=True,
        verbose_name='背景图审核通过'
    )
    
    # 钱包相关字段
    balance = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
        verbose_name='余额'
    )

     # 统计信息
    rating = models.FloatField(
        default=4.5,
        verbose_name='平均评分'
    )
    review_count = models.PositiveIntegerField(default=0)
    completed_orders = models.PositiveIntegerField(default=0)
    
    # 状态管理
    user_status = models.CharField(
        max_length=16,
        choices=USER_STATUS,
        default='active',
        verbose_name='用户状态'
    )
    city = models.CharField(max_length=50, blank=True, null=True,default='深圳')
    service_area = models.CharField(
        max_length=100,
        blank=True,
        verbose_name='服务区域'
    )
    last_login = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='最后登录时间'
    )
    
    # 联系方式
    phone_regex = RegexValidator(
        regex=r'^1[3-9]\d{9}$',
        message="手机号格式不正确"
    )
    phone_number = models.CharField(
        max_length=11,
        validators=[phone_regex],
        verbose_name='手机号'
    )
    email = models.EmailField(
        blank=True,
        verbose_name='邮箱'
    )

    
    # 元数据
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )

    
    class Meta:
        verbose_name = '厨师用户'
        verbose_name_plural = '厨师用户'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['openid']),
            models.Index(fields=['phone_number']),
            models.Index(fields=['verification_status']),
            models.Index(fields=['user_status']),
        ]
    
    def __str__(self):
        return f"{self.nickname or self.username} ({self.get_verification_status_display()})"
    
    @property
    def is_active(self):
        """判断用户是否活跃"""
        return self.user_status == 'active'
    
    @property
    def is_verified(self):
        """判断用户是否已认证"""
        return self.verification_status == 'verified'


class DjChefVerification(models.Model):
    """
    厨师认证信息模型
    """
    chef = models.OneToOneField(
        DjChef,
        on_delete=models.CASCADE,
        related_name='verification_info',
        verbose_name='关联厨师'
    )
    
    # 身份证信息
    id_card_number = models.CharField(
        max_length=18,
        null=True,
        verbose_name='身份证号'
    )
    id_card_front = models.URLField(
        max_length=500,
        null=True, 
        blank=True,
        verbose_name='身份证国徽面'
    )
    id_card_back = models.URLField(
        max_length=500,
        null=True, 
        blank=True,
        verbose_name='身份证人像面'
    )
    passport_image = models.URLField(
        max_length=500,
        null=True, 
        blank=True,
        verbose_name="护照图片URL"
    )
    
    # 健康证明
    health_certificate = models.URLField(
        max_length=500,
        null=True, 
        blank=True,
        verbose_name="健康证"
    )
    health_cert_expiry = models.DateField(
        null=True,
        verbose_name='健康证明有效期'
    )
    
    # 厨师资格证
    chef_certificate = models.URLField(
        max_length=500,
        null=True, 
        blank=True,
        verbose_name="厨师证"
    )
    
    # 其他信息
    years_of_experience = models.PositiveSmallIntegerField(
        default=0,
        null=True,
        verbose_name='从业年限'
    )
    specialty = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        verbose_name='擅长菜系'
    )
    
    # 审核信息
    reviewer_notes = models.TextField(
        blank=True,
        verbose_name='审核备注'
    )

    reviewer_approved = models.BooleanField(
        default=False,
        verbose_name='证件审核通过'
    )
    
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '厨师认证信息'
        verbose_name_plural = '厨师认证信息'
    
    def __str__(self):
        return f"{self.chef} 的认证信息"
    
class VerificationRecord(models.Model):
    """厨师认证审核记录"""
    chef = models.ForeignKey(
        DjChef, 
        on_delete=models.CASCADE,
        related_name='verification_records'
    )
    admin = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        related_name='chef_verifications'
    )
    id_front_verified = models.BooleanField(default=False)
    id_back_verified = models.BooleanField(default=False)
    health_cert_verified = models.BooleanField(default=False)
    chef_cert_verified = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name = '认证审核记录'
        verbose_name_plural = '认证审核记录'
        ordering = ['-created_at']